package com.hogan.hoganproject.contacts.mvp;

import com.hogan.hoganproject.contacts.ContactsUtils;
import com.hogan.hoganproject.contacts.adapter.ContactsItemBean;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Author: chenhu
 * Time: 2020/9/3 14:27
 * Description do somethings
 */
public class ContactsPresenter extends ContactsControl.CPresenter<ContactsControl.ContactsView> {
    public ContactsPresenter() {
    }

    @Override
    public void getContactsData() {
//          mView.showDialog();
        Disposable disposable = Observable.create(new ObservableOnSubscribe<List<ContactsItemBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<ContactsItemBean>> emitter) throws Exception {
                emitter.onNext(ContactsUtils.getInstance().getAllContacts());
            }
        }).subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mView.showDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(new Action() {
                    @Override
                    public void run() throws Exception {
                        mView.disDialog();
                    }
                })
                .subscribe(new Consumer<List<ContactsItemBean>>() {
                    @Override
                    public void accept(List<ContactsItemBean> contactsItemBeans) throws Exception {
                        mView.setContactsUI(contactsItemBeans);
                        mView.disDialog();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.fillInStackTrace();
                    }
                });
        addDisposable(disposable);
    }

}
